package ArrayTest;

import java.util.Scanner;

import static java.util.Arrays.binarySearch;

/*
二分法查找
    必须在有序数组中
 */
public class BinarySearchMethodTest {
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int[] arr = {1,3,5,7,9,10,15,21,23,43,55,63,67,81};
        //定义两个变量存储最左边和最右边下标
        int right = arr.length - 1;
        int left = 0;
        //接收想要查找的数
        int num = s.nextInt();
        int result = twoSearch(arr,right,left,num);
        System.out.println(result == -1?"未在数组中找到该元素":"找到了，该元素的下标为"+result);
    }


    //如果查找到了，就返回元素下标，未找到则返回-1；
    public static int twoSearch(int[] arr, int right, int left, int num){
        while(!(left > right)){        //如果左下标大于右下标，说明未找到该元素
            if(num > arr[(right+left) / 2]){  //条件成立时，要查找的元素在中间元素的右边
                left = (right+left) / 2 + 1;
            }else if((num < arr[(right+left) / 2])){ //条件成立时，要查找的元素在中间元素的左边
                right = (right+left) / 2 - 1;
            }else if((num == arr[(right+left) / 2])){ //元素成功找出
                return (right+left) / 2;
            }
        }
        return -1;
    }
}
